package com.qfedu.ssm.utils;

import com.qfedu.ssm.dao.PermissionDAO;
import com.qfedu.ssm.dao.RoleDAO;
import com.qfedu.ssm.dao.UserDAO;
import com.qfedu.ssm.pojos.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

public class MyRealm extends AuthorizingRealm {
    private PermissionDAO permissionDAO;
    private RoleDAO roleDAO;
    private UserDAO userDAO;
    public void setUserDAO(UserDAO userDAO) {
        this.userDAO = userDAO;
    }
    public void setPermissionDAO(PermissionDAO permissionDAO) {
        this.permissionDAO = permissionDAO;
    }
    public void setRoleDAO(RoleDAO roleDAO) {
        this.roleDAO = roleDAO;
    }

    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
       //获取授权用户的信息
        User user = (User)principalCollection.iterator().next();
        int userId = user.getId();
        Set<String> roles = roleDAO.queryRolesByUserId(userId);
        Set<String> permission = permissionDAO.queryPermissionByUserId(userId);
        //通过user的id查询用户的校色名
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        //通过user的id查询当前用户的所有权限
        authorizationInfo.setRoles(roles);
        authorizationInfo.setStringPermissions(permission);

        return authorizationInfo;
    }
    /**
     * 认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //1、从token中获取用户名
        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
        String username = token.getUsername();
        String password =new String(token.getPassword());
        //2、根据用户名查询数据库（UserDAO），得到一个User对象
        User user = userDAO.queryUserByName(username);

        if(user==null){
            throw new UnknownAccountException("账号不存在！");
        }else {
            String md5Pwd = new SimpleHash("MD5", password).toHex();
            //用户存在测验证密码
            if(!user.getUserPwd().equals(md5Pwd)){
                throw new IncorrectCredentialsException("密码错误！");
            }
        }
        return new SimpleAuthenticationInfo(user,password,getName());
    }
}
